<html lang="en-US">

<head>
    
<title>「连载十」定制 GORM Callbacks - 花落雨忧</title>

<meta property="og:title" content="「连载十」定制 GORM Callbacks - 花落雨忧">



    



    
    <meta property="description" content="GORM itself is powered by Callbacks, so you could fully customize GORM as you want
[&amp;hellip;] GORM 本身是由回调驱动的，所以我们可以根据需要完全定制 GORM，以此达到我们的目的，如下：
[&amp;hellip;] 在 GORM 中包含以上四类 Callbacks，我们结合项目选用 “替换现有的回调” 来解 &amp;hellip;">
    <meta property="og:description" content="GORM itself is powered by Callbacks, so you could fully customize GORM as you want
[&amp;hellip;] GORM 本身是由回调驱动的，所以我们可以根据需要完全定制 GORM，以此达到我们的目的，如下：
[&amp;hellip;] 在 GORM 中包含以上四类 Callbacks，我们结合项目选用 “替换现有的回调” 来解 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/gin/2018-04-15-gorm-callback/">「连载十」定制 GORM Callbacks</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/04/15</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="涉及知识点">涉及知识点</h2>
<ul>
<li>GORM</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<blockquote>
<p>GORM itself is powered by Callbacks, so you could fully customize GORM as you want</p>
</blockquote>
<p>GORM 本身是由回调驱动的，所以我们可以根据需要完全定制 GORM，以此达到我们的目的，如下：</p>
<ul>
<li>注册一个新的回调</li>
<li>删除现有的回调</li>
<li>替换现有的回调</li>
<li>注册回调的顺序</li>
</ul>
<p>在 GORM 中包含以上四类 Callbacks，我们结合项目选用 “替换现有的回调” 来解决一个小痛点。</p>
<h2 id="问题">问题</h2>
<p>在 models 目录下，我们包含 tag.go 和 article.go 两个文件，他们有一个问题，就是 BeforeCreate、BeforeUpdate 重复出现了，那难道 100 个文件，就要写一百次吗？</p>
<p>1、tag.go</p>
<p><img src="https://i.loli.net/2018/04/14/5ad20efdba409.jpg" alt="image"></p>
<p>2、article.go</p>
<p><img src="https://i.loli.net/2018/04/14/5ad20ebacc4c9.jpg" alt="image"></p>
<p>显然这是不可能的，如果先前你已经意识到这个问题，那挺 OK，但没有的话，现在开始就要改</p>
<h3 id="解决">解决</h3>
<p>在这里我们通过 Callbacks 来实现功能，不需要一个个文件去编写</p>
<h3 id="实现-callbacks">实现 Callbacks</h3>
<p>打开 models 目录下的 models.go 文件，实现以下两个方法：</p>
<p>1、updateTimeStampForCreateCallback</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// updateTimeStampForCreateCallback will set `CreatedOn`, `ModifiedOn` when creating
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">updateTimeStampForCreateCallback</span>(<span style="color:#a6e22e">scope</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gorm</span>.<span style="color:#a6e22e">Scope</span>) {
    <span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">HasError</span>() {
        <span style="color:#a6e22e">nowTime</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Unix</span>()
        <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">createTimeField</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">FieldByName</span>(<span style="color:#e6db74">&#34;CreatedOn&#34;</span>); <span style="color:#a6e22e">ok</span> {
            <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">createTimeField</span>.<span style="color:#a6e22e">IsBlank</span> {
                <span style="color:#a6e22e">createTimeField</span>.<span style="color:#a6e22e">Set</span>(<span style="color:#a6e22e">nowTime</span>)
            }
        }

        <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">modifyTimeField</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">FieldByName</span>(<span style="color:#e6db74">&#34;ModifiedOn&#34;</span>); <span style="color:#a6e22e">ok</span> {
            <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">modifyTimeField</span>.<span style="color:#a6e22e">IsBlank</span> {
                <span style="color:#a6e22e">modifyTimeField</span>.<span style="color:#a6e22e">Set</span>(<span style="color:#a6e22e">nowTime</span>)
            }
        }
    }
}
</code></pre></div><p>在这段方法中，会完成以下功能</p>
<ul>
<li>检查是否有含有错误（db.Error）</li>
<li><code>scope.FieldByName</code> 通过 <code>scope.Fields()</code> 获取所有字段，判断当前是否包含所需字段</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">field</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Fields</span>() {
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">field</span>.<span style="color:#a6e22e">Name</span> <span style="color:#f92672">==</span> <span style="color:#a6e22e">name</span> <span style="color:#f92672">||</span> <span style="color:#a6e22e">field</span>.<span style="color:#a6e22e">DBName</span> <span style="color:#f92672">==</span> <span style="color:#a6e22e">name</span> {
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">field</span>, <span style="color:#66d9ef">true</span>
    }
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">field</span>.<span style="color:#a6e22e">DBName</span> <span style="color:#f92672">==</span> <span style="color:#a6e22e">dbName</span> {
        <span style="color:#a6e22e">mostMatchedField</span> = <span style="color:#a6e22e">field</span>
    }
}
</code></pre></div><ul>
<li><code>field.IsBlank</code> 可判断该字段的值是否为空</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">isBlank</span>(<span style="color:#a6e22e">value</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Value</span>) <span style="color:#66d9ef">bool</span> {
    <span style="color:#66d9ef">switch</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Kind</span>() {
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">String</span>:
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Len</span>() <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Bool</span>:
        <span style="color:#66d9ef">return</span> !<span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Bool</span>()
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Int</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Int8</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Int16</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Int32</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Int64</span>:
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Int</span>() <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uint</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uint8</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uint16</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uint32</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uint64</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Uintptr</span>:
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Uint</span>() <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Float32</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Float64</span>:
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Float</span>() <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>
    <span style="color:#66d9ef">case</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Interface</span>, <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Ptr</span>:
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">IsNil</span>()
    }

    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">DeepEqual</span>(<span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Interface</span>(), <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Zero</span>(<span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">Type</span>()).<span style="color:#a6e22e">Interface</span>())
}
</code></pre></div><ul>
<li>若为空则 <code>field.Set</code> 用于给该字段设置值，参数为 <code>interface{}</code></li>
</ul>
<p>2、updateTimeStampForUpdateCallback</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// updateTimeStampForUpdateCallback will set `ModifyTime` when updating
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">updateTimeStampForUpdateCallback</span>(<span style="color:#a6e22e">scope</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gorm</span>.<span style="color:#a6e22e">Scope</span>) {
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Get</span>(<span style="color:#e6db74">&#34;gorm:update_column&#34;</span>); !<span style="color:#a6e22e">ok</span> {
        <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">SetColumn</span>(<span style="color:#e6db74">&#34;ModifiedOn&#34;</span>, <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Unix</span>())
    }
}
</code></pre></div><ul>
<li><code>scope.Get(...)</code> 根据入参获取设置了字面值的参数，例如本文中是 <code>gorm:update_column</code> ，它会去查找含这个字面值的字段属性</li>
<li><code>scope.SetColumn(...)</code> 假设没有指定 <code>update_column</code> 的字段，我们默认在更新回调设置 <code>ModifiedOn</code> 的值</li>
</ul>
<h3 id="注册-callbacks">注册 Callbacks</h3>
<p>在上面小节我已经把回调方法编写好了，接下来需要将其注册进 GORM 的钩子里，但其本身自带 Create 和 Update 回调，因此调用替换即可</p>
<p>在 models.go 的 init 函数中，增加以下语句</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Callback</span>().<span style="color:#a6e22e">Create</span>().<span style="color:#a6e22e">Replace</span>(<span style="color:#e6db74">&#34;gorm:update_time_stamp&#34;</span>, <span style="color:#a6e22e">updateTimeStampForCreateCallback</span>)
<span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Callback</span>().<span style="color:#a6e22e">Update</span>().<span style="color:#a6e22e">Replace</span>(<span style="color:#e6db74">&#34;gorm:update_time_stamp&#34;</span>, <span style="color:#a6e22e">updateTimeStampForUpdateCallback</span>)
</code></pre></div><h3 id="验证">验证</h3>
<p>访问 AddTag 接口，成功后检查数据库，可发现 <code>created_on</code> 和 <code>modified_on</code> 字段都为当前执行时间</p>
<p>访问 EditTag 接口，可发现 <code>modified_on</code> 为最后一次执行更新的时间</p>
<h2 id="拓展">拓展</h2>
<p>我们想到，在实际项目中硬删除是较少存在的，那么是否可以通过 Callbacks 来完成这个功能呢？</p>
<p>答案是可以的，我们在先前 <code>Model struct</code> 增加 <code>DeletedOn</code> 变量</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Model</span> <span style="color:#66d9ef">struct</span> {
    <span style="color:#a6e22e">ID</span> <span style="color:#66d9ef">int</span> <span style="color:#e6db74">`gorm:&#34;primary_key&#34; json:&#34;id&#34;`</span>
    <span style="color:#a6e22e">CreatedOn</span> <span style="color:#66d9ef">int</span> <span style="color:#e6db74">`json:&#34;created_on&#34;`</span>
    <span style="color:#a6e22e">ModifiedOn</span> <span style="color:#66d9ef">int</span> <span style="color:#e6db74">`json:&#34;modified_on&#34;`</span>
    <span style="color:#a6e22e">DeletedOn</span> <span style="color:#66d9ef">int</span> <span style="color:#e6db74">`json:&#34;deleted_on&#34;`</span>
}
</code></pre></div><h3 id="实现-callbacks-1">实现 Callbacks</h3>
<p>打开 models 目录下的 models.go 文件，实现以下方法：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">deleteCallback</span>(<span style="color:#a6e22e">scope</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gorm</span>.<span style="color:#a6e22e">Scope</span>) {
    <span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">HasError</span>() {
        <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">extraOption</span> <span style="color:#66d9ef">string</span>
        <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">str</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Get</span>(<span style="color:#e6db74">&#34;gorm:delete_option&#34;</span>); <span style="color:#a6e22e">ok</span> {
            <span style="color:#a6e22e">extraOption</span> = <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprint</span>(<span style="color:#a6e22e">str</span>)
        }

        <span style="color:#a6e22e">deletedOnField</span>, <span style="color:#a6e22e">hasDeletedOnField</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">FieldByName</span>(<span style="color:#e6db74">&#34;DeletedOn&#34;</span>)

        <span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Search</span>.<span style="color:#a6e22e">Unscoped</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">hasDeletedOnField</span> {
            <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Raw</span>(<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(
                <span style="color:#e6db74">&#34;UPDATE %v SET %v=%v%v%v&#34;</span>,
                <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">QuotedTableName</span>(),
                <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Quote</span>(<span style="color:#a6e22e">deletedOnField</span>.<span style="color:#a6e22e">DBName</span>),
                <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">AddToVars</span>(<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Unix</span>()),
                <span style="color:#a6e22e">addExtraSpaceIfExist</span>(<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">CombinedConditionSql</span>()),
                <span style="color:#a6e22e">addExtraSpaceIfExist</span>(<span style="color:#a6e22e">extraOption</span>),
            )).<span style="color:#a6e22e">Exec</span>()
        } <span style="color:#66d9ef">else</span> {
            <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Raw</span>(<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(
                <span style="color:#e6db74">&#34;DELETE FROM %v%v%v&#34;</span>,
                <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">QuotedTableName</span>(),
                <span style="color:#a6e22e">addExtraSpaceIfExist</span>(<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">CombinedConditionSql</span>()),
                <span style="color:#a6e22e">addExtraSpaceIfExist</span>(<span style="color:#a6e22e">extraOption</span>),
            )).<span style="color:#a6e22e">Exec</span>()
        }
    }
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">addExtraSpaceIfExist</span>(<span style="color:#a6e22e">str</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span> {
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">str</span> <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;&#34;</span> {
        <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34; &#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">str</span>
    }
    <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;&#34;</span>
}
</code></pre></div><ul>
<li><code>scope.Get(&quot;gorm:delete_option&quot;)</code> 检查是否手动指定了 delete_option</li>
<li><code>scope.FieldByName(&quot;DeletedOn&quot;)</code> 获取我们约定的删除字段，若存在则 <code>UPDATE</code> 软删除，若不存在则 <code>DELETE</code> 硬删除</li>
<li><code>scope.QuotedTableName()</code> 返回引用的表名，这个方法 GORM 会根据自身逻辑对表名进行一些处理</li>
<li><code>scope.CombinedConditionSql()</code> 返回组合好的条件 SQL，看一下方法原型很明了</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">scope</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Scope</span>) <span style="color:#a6e22e">CombinedConditionSql</span>() <span style="color:#66d9ef">string</span> {
    <span style="color:#a6e22e">joinSQL</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">joinsSQL</span>()
    <span style="color:#a6e22e">whereSQL</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">whereSQL</span>()
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Search</span>.<span style="color:#a6e22e">raw</span> {
        <span style="color:#a6e22e">whereSQL</span> = <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">TrimSuffix</span>(<span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">TrimPrefix</span>(<span style="color:#a6e22e">whereSQL</span>, <span style="color:#e6db74">&#34;WHERE (&#34;</span>), <span style="color:#e6db74">&#34;)&#34;</span>)
    }
    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">joinSQL</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">whereSQL</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">groupSQL</span>() <span style="color:#f92672">+</span>
        <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">havingSQL</span>() <span style="color:#f92672">+</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">orderSQL</span>() <span style="color:#f92672">+</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">limitAndOffsetSQL</span>()
}
</code></pre></div><ul>
<li><code>scope.AddToVars</code> 该方法可以添加值作为 SQL 的参数，也可用于防范 SQL 注入</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">scope</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Scope</span>) <span style="color:#a6e22e">AddToVars</span>(<span style="color:#a6e22e">value</span> <span style="color:#66d9ef">interface</span>{}) <span style="color:#66d9ef">string</span> {
    <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">skipBindVar</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">InstanceGet</span>(<span style="color:#e6db74">&#34;skip_bindvar&#34;</span>)

    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">expr</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">value</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">expr</span>); <span style="color:#a6e22e">ok</span> {
        <span style="color:#a6e22e">exp</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">expr</span>.<span style="color:#a6e22e">expr</span>
        <span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">arg</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">expr</span>.<span style="color:#a6e22e">args</span> {
            <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">skipBindVar</span> {
                <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">AddToVars</span>(<span style="color:#a6e22e">arg</span>)
            } <span style="color:#66d9ef">else</span> {
                <span style="color:#a6e22e">exp</span> = <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">Replace</span>(<span style="color:#a6e22e">exp</span>, <span style="color:#e6db74">&#34;?&#34;</span>, <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">AddToVars</span>(<span style="color:#a6e22e">arg</span>), <span style="color:#ae81ff">1</span>)
            }
        }
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">exp</span>
    }

    <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">SQLVars</span> = append(<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">SQLVars</span>, <span style="color:#a6e22e">value</span>)

    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">skipBindVar</span> {
        <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;?&#34;</span>
    }
    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">Dialect</span>().<span style="color:#a6e22e">BindVar</span>(len(<span style="color:#a6e22e">scope</span>.<span style="color:#a6e22e">SQLVars</span>))
}
</code></pre></div><h3 id="注册-callbacks-1">注册 Callbacks</h3>
<p>在 models.go 的 init 函数中，增加以下删除的回调</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Callback</span>().<span style="color:#a6e22e">Delete</span>().<span style="color:#a6e22e">Replace</span>(<span style="color:#e6db74">&#34;gorm:delete&#34;</span>, <span style="color:#a6e22e">deleteCallback</span>)
</code></pre></div><h3 id="验证-1">验证</h3>
<p>重启服务，访问 DeleteTag 接口，成功后即可发现 deleted_on 字段有值</p>
<h2 id="小结">小结</h2>
<p>在这一章节中，我们结合 GORM 完成了新增、更新、查询的 Callbacks，在实际项目中常常也是这么使用</p>
<p>毕竟，一个钩子的事，就没有必要自己手写过多不必要的代码了</p>
<p>（注意，增加了软删除后，先前的代码需要增加 <code>deleted_on</code> 的判断）</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h3 id="文档">文档</h3>
<ul>
<li><a href="http://gorm.io/docs/write_plugins.html">gorm</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-26-cgo/">「番外」Golang 交叉编译</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-24-golang-docker/">「连载九」将Golang应用部署到Docker</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-18-swagger/">「连载八」为它加上Swagger</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-15-reload-http/">「连载七」优雅的重启服务</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-02-15-log/">「连载六」编写一个简单的文件日志</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/crawler/2018-04-01-cars/"
                                                    rel="prev">爬取汽车之家 二手车产品库</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/crawler/2018-04-28-go2018/">了解一下Golang的市场行情</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>